<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="模型类型" prop="modelType">
        <el-select
          v-model="queryParams.modelType"
          placeholder="选择模型类型"
          clearable
          style="width: 120px"
        >
          <el-option label="YOLO" value="yolo" />
          <el-option label="R-CNN" value="rcnn" />
          <el-option label="移动端" value="mobile" />
          <el-option label="自定义" value="custom" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isActive">
        <el-select
          v-model="queryParams.isActive"
          placeholder="选择状态"
          clearable
          style="width: 100px"
        >
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否免费" prop="isFree">
        <el-select
          v-model="queryParams.isFree"
          placeholder="选择类型"
          clearable
          style="width: 100px"
        >
          <el-option label="免费" value="1" />
          <el-option label="付费" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:fishDetectionModel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:fishDetectionModel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fishDetectionModel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:fishDetectionModel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="fishDetectionModelList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="modelId" width="80" />
      <el-table-column label="模型名称" align="left" prop="modelName" min-width="150" show-overflow-tooltip />
      <el-table-column label="类型" align="center" prop="modelType" width="80">
        <template slot-scope="scope">
          <el-tag :type="getModelTypeTag(scope.row.modelType)" size="mini">
            {{ getModelTypeText(scope.row.modelType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="版本" align="center" prop="modelVersion" width="80" />
      <el-table-column label="准确率" align="center" prop="accuracyRate" width="100">
        <template slot-scope="scope">
          <el-progress 
            :percentage="scope.row.accuracyRate" 
            :stroke-width="8"
            :show-text="true"
            :color="getAccuracyColor(scope.row.accuracyRate)"
          />
        </template>
      </el-table-column>
      <el-table-column label="置信度" align="center" prop="confidenceThreshold" width="80" />
      <el-table-column label="处理时间(ms)" align="center" prop="avgProcessingTime" width="100" />
      <el-table-column label="启用" align="center" prop="isActive" width="70">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isActive"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="免费" align="center" prop="isFree" width="70">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isFree === '1' ? 'success' : 'warning'" size="mini">
            {{ scope.row.isFree === '1' ? '免费' : '付费' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支持物种" align="left" prop="supportSpecies" min-width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="scope.row.supportSpecies">
            <el-tag 
              v-for="(species, index) in getSupportSpeciesList(scope.row.supportSpecies)" 
              :key="index" 
              size="mini" 
              style="margin: 1px"
            >
              {{ species }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="下载地址" align="left" prop="downloadUrl" min-width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link 
            v-if="scope.row.downloadUrl" 
            :href="scope.row.downloadUrl" 
            type="primary" 
            target="_blank"
            :underline="false"
          >
            <i class="el-icon-download"></i> 下载
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:fishDetectionModel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:fishDetectionModel:remove']"
            style="color: #f56c6c"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改鱼类检测模型管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模型名称" prop="modelName">
              <el-input v-model="form.modelName" placeholder="请输入模型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型类型" prop="modelType">
              <el-select v-model="form.modelType" placeholder="请选择模型类型" style="width: 100%">
                <el-option label="YOLO系列目标检测" value="yolo" />
                <el-option label="R-CNN系列精确检测" value="rcnn" />
                <el-option label="移动端轻量模型" value="mobile" />
                <el-option label="自定义模型" value="custom" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型版本" prop="modelVersion">
              <el-input v-model="form.modelVersion" placeholder="如：v8.0, v2.0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件大小(MB)" prop="modelSize">
              <el-input-number 
                v-model="form.modelSizeMB" 
                :min="0" 
                :max="10000" 
                :precision="2"
                controls-position="right"
                style="width: 100%"
                @change="handleModelSizeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模型文件路径" prop="modelPath">
              <el-input v-model="form.modelPath" placeholder="/models/yolov8n.pt" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="置信度阈值" prop="confidenceThreshold">
              <el-slider
                v-model="form.confidenceThreshold"
                :min="0"
                :max="1"
                :step="0.01"
                :format-tooltip="formatConfidenceTooltip"
                show-input
                :show-input-controls="false"
                input-size="mini"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="准确率(%)" prop="accuracyRate">
              <el-input-number 
                v-model="form.accuracyRate" 
                :min="0" 
                :max="100" 
                :precision="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理时间(ms)" prop="avgProcessingTime">
              <el-input-number 
                v-model="form.avgProcessingTime" 
                :min="0" 
                :max="10000"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态设置">
              <div style="display: flex; gap: 20px;">
                <div>
                  <span style="margin-right: 10px;">是否启用</span>
                  <el-switch
                    v-model="form.isActive"
                    active-value="1"
                    inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  />
                </div>
                <div>
                  <span style="margin-right: 10px;">是否免费</span>
                  <el-switch
                    v-model="form.isFree"
                    active-value="1"
                    inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  />
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="支持检测物种" prop="supportSpecies">
              <el-input 
                v-model="form.supportSpeciesText" 
                placeholder="请输入支持的鱼类，用逗号分隔，如：fish,salmon,trout,bass"
                @blur="handleSpeciesChange"
              />
              <div style="margin-top: 5px;">
                <el-tag 
                  v-for="(species, index) in getSupportSpeciesList(form.supportSpecies)" 
                  :key="index" 
                  size="mini" 
                  closable
                  @close="removeSpecies(index)"
                  style="margin: 2px"
                >
                  {{ species }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="下载地址" prop="downloadUrl">
              <el-input v-model="form.downloadUrl" placeholder="https://example.com/model.pt" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模型描述" prop="modelDescription">
              <el-input 
                v-model="form.modelDescription" 
                type="textarea" 
                :rows="3"
                placeholder="请描述模型的特点、适用场景等"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                :rows="2"
                placeholder="其他说明信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFishDetectionModel, getFishDetectionModel, delFishDetectionModel, addFishDetectionModel, updateFishDetectionModel } from "@/api/system/fishDetectionModel";

export default {
  name: "FishDetectionModel",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 鱼类检测模型管理表格数据
      fishDetectionModelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        modelType: null,
        modelVersion: null,
        modelPath: null,
        modelSize: null,
        confidenceThreshold: null,
        supportSpecies: null,
        modelDescription: null,
        isActive: null,
        isFree: null,
        downloadUrl: null,
        accuracyRate: null,
        avgProcessingTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" }
        ],
        modelType: [
          { required: true, message: "模型类型(yolo=YOLO系列目标检测/rcnn=R-CNN系列精确检测/mobile=移动端轻量模型/custom=自定义模型)不能为空", trigger: "change" }
        ],
        modelVersion: [
          { required: true, message: "模型版本不能为空", trigger: "blur" }
        ],
        modelPath: [
          { required: true, message: "模型文件路径不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询鱼类检测模型管理列表 */
    getList() {
      this.loading = true;
      listFishDetectionModel(this.queryParams).then(response => {
        this.fishDetectionModelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: null,
        modelName: null,
        modelType: 'yolo',
        modelVersion: null,
        modelPath: null,
        modelSize: null,
        modelSizeMB: null,
        confidenceThreshold: 0.5,
        supportSpecies: null,
        supportSpeciesText: '',
        modelDescription: null,
        isActive: '1',
        isFree: '1',
        downloadUrl: null,
        accuracyRate: null,
        avgProcessingTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.modelId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加鱼类检测模型管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modelId = row.modelId || this.ids
      getFishDetectionModel(modelId).then(response => {
        this.form = response.data;
        // 处理文件大小转换
        this.form.modelSizeMB = this.form.modelSize ? (this.form.modelSize / (1024 * 1024)).toFixed(2) : null;
        // 处理物种文本
        this.form.supportSpeciesText = this.getSupportSpeciesList(this.form.supportSpecies).join(',');
        this.open = true;
        this.title = "修改鱼类检测模型管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.modelId != null) {
            updateFishDetectionModel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFishDetectionModel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$modal.confirm('是否确认删除鱼类检测模型管理编号为"' + modelIds + '"的数据项？').then(function() {
        return delFishDetectionModel(modelIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/fishDetectionModel/export', {
        ...this.queryParams
      }, `fishDetectionModel_${new Date().getTime()}.xlsx`)
    },
    // 获取模型类型标签样式
    getModelTypeTag(type) {
      const tagTypes = {
        'yolo': 'primary',
        'rcnn': 'success', 
        'mobile': 'warning',
        'custom': 'info'
      };
      return tagTypes[type] || 'info';
    },
    // 获取模型类型显示文本
    getModelTypeText(type) {
      const texts = {
        'yolo': 'YOLO',
        'rcnn': 'R-CNN',
        'mobile': '移动端',
        'custom': '自定义'
      };
      return texts[type] || type;
    },
    // 获取准确率颜色
    getAccuracyColor(value) {
      if (value >= 90) return '#67c23a';
      if (value >= 80) return '#e6a23c';
      if (value >= 70) return '#f56c6c';
      return '#909399';
    },
    // 获取支持物种列表
    getSupportSpeciesList(supportSpecies) {
      if (!supportSpecies) return [];
      try {
        return JSON.parse(supportSpecies);
      } catch (e) {
        return supportSpecies.split(',').map(s => s.trim()).filter(s => s);
      }
    },
    // 处理状态变更
    handleStatusChange(row) {
      updateFishDetectionModel(row).then(response => {
        this.$modal.msgSuccess("状态更新成功");
      }).catch(() => {
        // 回滚状态
        row.isActive = row.isActive === '1' ? '0' : '1';
      });
    },
    // 格式化置信度提示
    formatConfidenceTooltip(val) {
      return (val * 100).toFixed(0) + '%';
    },
    // 处理文件大小变更
    handleModelSizeChange(value) {
      this.form.modelSize = value ? Math.round(value * 1024 * 1024) : null;
    },
    // 处理物种变更
    handleSpeciesChange() {
      if (this.form.supportSpeciesText) {
        const species = this.form.supportSpeciesText.split(',').map(s => s.trim()).filter(s => s);
        this.form.supportSpecies = JSON.stringify(species);
      } else {
        this.form.supportSpecies = null;
      }
    },
    // 移除物种
    removeSpecies(index) {
      const species = this.getSupportSpeciesList(this.form.supportSpecies);
      species.splice(index, 1);
      this.form.supportSpecies = JSON.stringify(species);
      this.form.supportSpeciesText = species.join(',');
    }
  }
};
</script>
